package com.rpframework.module.common.springmvc.interceptor;

import com.rpframework.module.common.config.Config;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口跨域
 *
 * @author 刘兴
 */
public class CrossDomainInterceptor extends HandlerInterceptorAdapter {

    @Qualifier("config")
    @Autowired
    private Config config;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String CORSDomain = config.getCORSDomain();

        //自定义跨域
        String CORSDomainPar = request.getParameter("CORSDomain");
        if (!StringUtils.isBlank(CORSDomainPar)) {
            CORSDomain = CORSDomainPar;
        }

        if (!CORSDomain.trim().equals("*")) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }
        response.setHeader("Access-Control-Allow-Origin", CORSDomain);
        response.setHeader("Access-Control-Allow-Headers", "*, X-Requested-With, Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


}